package com.vitabuybuy.tv.ui.mine.talent.notice

import android.app.Activity
import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.os.bundleOf
import androidx.lifecycle.Observer
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.LinearLayoutManager
import com.library.common.base.BaseActivity
import com.library.common.base.MessageModel
import com.library.common.toast.XToast
import com.library.common.util.PictureUtils
import com.luck.picture.lib.PictureSelector
import com.tencent.imsdk.TIMConversationType
import com.tencent.qcloud.tim.uikit.modules.chat.base.ChatInfo
import com.vitabuybuy.tv.R
import com.vitabuybuy.tv.databinding.ActivityPlantGrassNoticeDetailBinding
import com.vitabuybuy.tv.ui.mine.order.adapter.PictureAdapter
import com.vitabuybuy.tv.ui.mine.talent.notice.adapter.LogisticsAdapter
import com.vitabuybuy.tv.ui.mine.talent.notice.adapter.VoucherAdapter
import com.vitabuybuy.tv.ui.mine.talent.notice.viewmodel.NoticeViewModel
import com.vitabuybuy.tv.ui.mine.talent.task.adapter.TaskGoodAdapter
import com.vitabuybuy.tv.ui.tencent.chat.ChatActivity
import com.vitabuybuy.tv.utils.StringUtil
import com.yanzhenjie.permission.AndPermission
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.android.synthetic.main.activity_plant_grass_notice_detail.*

class PlantGrassNoticeDetailActivity :
    BaseActivity<NoticeViewModel, ActivityPlantGrassNoticeDetailBinding>() {
    override val isUseBaseTitleBar: Boolean
        get() = true
    override val layoutId: Int
        get() = R.layout.activity_plant_grass_notice_detail

    private var noticeId : Int?= -1
    private val goodAdapter by lazy { TaskGoodAdapter(true) }
    private val voucherAdapter by lazy { VoucherAdapter() }
    private val logisticsAdapter by lazy { LogisticsAdapter() }
    private val picAdapter by lazy { PictureAdapter(3) }
    private var REQUEST_CODE_CAMMER = 0x11


    override fun onGetBundle(bundle: Bundle?) {
        noticeId = bundle?.getInt("noticeId")
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitle(getString(R.string.task_detail))
        mBinding.mViewModel = viewModel
        lvGoods.apply {
            adapter = goodAdapter
            layoutManager = LinearLayoutManager(mContext)
            isNestedScrollingEnabled = false
        }
        rlLogistics.apply {
            adapter = logisticsAdapter
            layoutManager = LinearLayoutManager(mContext)
            isNestedScrollingEnabled = false
        }
        rl_alreadyPic.apply {
            adapter = voucherAdapter
            layoutManager = GridLayoutManager(mContext, 4)
            isNestedScrollingEnabled = false
        }
        rl_CredentialsPic.apply {
            adapter = picAdapter
            layoutManager = GridLayoutManager(mContext, 4)
            isNestedScrollingEnabled = false
        }
    }

    override fun observeData() {
        viewModel.getNoticDetails(noticeId)
        viewModel.noticeDetail.observe(this, Observer {
            when (it.status) {
                getString(R.string.wait_to_deliver) -> {
                    rlLogistics.visibility = View.GONE
                    tvCredentials_1.visibility = View.GONE
                    rl_alreadyPic.visibility = View.GONE
                    tvNoPassResonHint.visibility = View.GONE
                    tvNoPassReson.visibility = View.GONE
                    tvCredentials_2.visibility = View.GONE
                    rl_CredentialsPic.visibility = View.GONE
                    btnConfirmReceive.visibility = View.GONE
                }
                getString(R.string.wait_to_receive) -> {
                    rlLogistics.visibility = View.VISIBLE
                    tvCredentials_1.visibility = View.GONE
                    rl_alreadyPic.visibility = View.GONE
                    tvNoPassResonHint.visibility = View.GONE
                    tvNoPassReson.visibility = View.GONE
                    tvCredentials_2.visibility = View.GONE
                    rl_CredentialsPic.visibility = View.GONE
                    btnConfirmReceive.visibility = View.VISIBLE
                    btnConfirmReceive.text = getString(R.string.confirm_receive)
                }
                getString(R.string.wait_to_deal) -> {
                    rlLogistics.visibility = View.VISIBLE
                    tvCredentials_1.visibility = View.GONE
                    rl_alreadyPic.visibility = View.GONE
                    tvNoPassResonHint.visibility = View.GONE
                    tvNoPassReson.visibility = View.GONE
                    tvCredentials_2.visibility = View.VISIBLE
                    rl_CredentialsPic.visibility = View.VISIBLE
                    btnConfirmReceive.visibility = View.VISIBLE
                    btnConfirmReceive.text = getString(R.string.submit)
                }
                getString(R.string.wait_auth) -> {
                    rlLogistics.visibility = View.VISIBLE
                    tvCredentials_1.visibility = View.VISIBLE
                    rl_alreadyPic.visibility = View.VISIBLE
                    tvNoPassResonHint.visibility = View.GONE
                    tvNoPassReson.visibility = View.GONE
                    tvCredentials_2.visibility = View.GONE
                    rl_CredentialsPic.visibility = View.GONE
                    btnConfirmReceive.visibility = View.GONE
                }
                getString(R.string.no_pass) -> {
                    rlLogistics.visibility = View.VISIBLE
                    tvCredentials_1.visibility = View.VISIBLE
                    rl_alreadyPic.visibility = View.VISIBLE
                    tvNoPassResonHint.visibility = View.VISIBLE
                    tvNoPassReson.visibility = View.VISIBLE
                    tvCredentials_2.visibility = View.VISIBLE
                    rl_CredentialsPic.visibility = View.VISIBLE
                    btnConfirmReceive.visibility = View.VISIBLE
                    tvNoPassReson.text = it.refuseReason
                    btnConfirmReceive.text = getString(R.string.submit)
                }
                getString(R.string.already_pass) -> {
                    rlLogistics.visibility = View.VISIBLE
                    tvCredentials_1.visibility = View.VISIBLE
                    rl_alreadyPic.visibility = View.VISIBLE
                    tvNoPassResonHint.visibility = View.GONE
                    tvNoPassReson.visibility = View.GONE
                    tvCredentials_2.visibility = View.GONE
                    rl_CredentialsPic.visibility = View.GONE
                    btnConfirmReceive.visibility = View.GONE
                }
            }
            tvName.text = it.store.name
            tvRequirement.text = it.task.title
            tvRequirementContent.text = String.format(
                getString(R.string.task_requirement),
                it.task.content
            )
            tvTiChengRequirement.text = when (it.commissionType) {
                "提成金额" -> String.format(getString(R.string.ticheng_requirement), it.commission)
                "佣金" -> String.format(getString(R.string.youjin_requirement), it.commission)
                else -> String.format(getString(R.string.yikoujia_requirement), it.commission)
            }
            tvAreaRequirement.text =
                String.format(getString(R.string.area_requirement), it.label.name)
            tvFansRequirement.text =
                String.format(getString(R.string.fans_requirement), it.task.fansQuantity)
            tvReceiverAddressDetail.text =
                String.format(getString(R.string.deliver_address_2), it.task.address.addressDetail)
            tvLogisticsStatus.text =
                String.format(
                    getString(R.string.deliver_status),
                    if (it.courier.name.isNullOrEmpty()) "暂无物流" else it.courier.name
                )
            goodAdapter.setNewData(it.task.productList)
            if (!it.completeImages.isNullOrEmpty()) {
                voucherAdapter.setNewData(it.completeImages.split(","))
            }
            for (abc in 0..4) {
                logisticsAdapter.addData(
                    "2020-05-25/周一/04:40:52 商品已经下单\n19:16:26 包裹正在等待揽收"
                )
            }
        })
    }

    private fun copy(content: String) {
        // 获取系统剪贴板
        val clipboard = getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
        // 创建一个剪贴数据集，包含一个普通文本数据条目（需要复制的数据）
        val clipData = ClipData.newPlainText(null, content)
        // 把数据集设置（复制）到剪贴板
        clipboard.setPrimaryClip(clipData)
    }

    override fun eventHandling() {
        mBinding.btnChatNow.setOnClickListener {
            viewModel.noticeDetail.value?.run {
                val chatInfo = ChatInfo()
                chatInfo.type = TIMConversationType.C2C
                chatInfo.id = this.store.id.toString()
                chatInfo.chatName = this.store.name
                ChatActivity.openActivity(mContext, chatInfo)
            }
        }
        goodAdapter.itemCopyLinkListener = {
            val copyLink = viewModel.noticeDetail.value?.agreementShareLinkList?.get(it)?.link
            copyLink?.run {
                copy(this)
                XToast.success("复制成功")
            }
        }
        btnConfirmReceive.setOnClickListener {
            if (btnConfirmReceive.text.toString() == getString(R.string.confirm_receive)) {
                AlertDialog.Builder(mContext)
                    .setTitle(getString(R.string.logout))
                    .setMessage(getString(R.string.are_you_sure_confir_receiver))
                    .setCancelable(true)
                    .setPositiveButton(getString(R.string.confirm)) { _, _ ->
                        viewModel.comfirmReceiver(
                            mapOf(
                                Pair(
                                    "id",
                                    viewModel.noticeDetail.value?.id
                                )
                            )
                        )
                    }
                    .setNegativeButton(getString(R.string.cancel)) { _, _ -> }.create()
                    .show()
            } else {
                if (picAdapter.mData.isEmpty()) {
                    XToast.normal(getString(R.string.please_upload_pingzheng))
                } else {
                    val params = HashMap<String, Any?>()
                    var images = ""
                    for (image in picAdapter.mData) {
                        images = "$images$image,"
                    }
                    params["completeImages"] = StringUtil.replaceEndChar(images)
                    params["id"] = viewModel.noticeDetail.value?.id
                    viewModel.applyAuth(params)
                }
            }
        }
        picAdapter.setOnItemClickListener { _, position ->
            if (position == picAdapter.mData.size) {
                AndPermission.with(this)
                    .runtime()
                    .permission(
                        Permission.Group.CAMERA,
                        Permission.Group.STORAGE
                    )
                    .onDenied {
                        if (AndPermission.hasAlwaysDeniedPermission(this, it)) {
                            // 这些权限被用户总是拒绝。
                            XToast.normal(getString(R.string.request_necessary_permissions))
                        }
                    }
                    .onGranted {
                        PictureUtils.openAluamMore(
                            mContext,
                            REQUEST_CODE_CAMMER,
                            (3 - picAdapter.mData.size)
                        )
                    }.start()
            }
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode != Activity.RESULT_OK) return
        if (requestCode == REQUEST_CODE_CAMMER) {
            val images = ArrayList<String>()
            for (image in PictureSelector.obtainMultipleResult(data)) {
                images.add(image.compressPath)
            }
            viewModel.uploadImage(images)
        }
    }

    override fun handleEvent(msg: MessageModel) {
        when (msg.code) {
            0,1 -> {
                viewModel.getNoticDetails(noticeId)
            }
            2 -> {
                if (picAdapter.mData.size == 0)
                    picAdapter.setNewData(msg.obj as ArrayList<String>)
                else
                    picAdapter.addData(msg.obj as ArrayList<String>)
            }
        }
    }

    companion object {
        fun openActivity(mContext: BaseActivity<*, *>, noticeId: Int) {
            mContext.startActivity(
                bundleOf(Pair("noticeId", noticeId)),
                PlantGrassNoticeDetailActivity::class.java
            )
        }
    }
}
